package com.express.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.express.entity.User;
import com.express.result.Result;
import com.express.service.IUsersService;
import com.express.utils.AliOssUtil;
import com.express.utils.BaseContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@Slf4j
@RestController
@RequestMapping("/user/common")
@Api(tags = "通用接口")
@RequiredArgsConstructor
public class CommonController {

    private final AliOssUtil ossUtil;
    private final IUsersService usersService;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestParam("avatar") MultipartFile file) {
        log.info("文件上传:{}", file);

        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();

            // 获取原始文件名的后缀 dfdf.jpg                  从最后一个点开始截取
            String extension = null;
            if (originalFilename != null) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            //构建新文件名称
            String filename = UUID.randomUUID().toString() + extension;

            // 文件的请求路径
            String url = ossUtil.upload(file.getBytes(), filename);
            // 更新用户头像URL
            User userToUpdate = new User();
            userToUpdate.setAvatar(url);

            // 使用 BaseContext 获取当前用户的 userId
            Long userId = BaseContext.getCurrentId();
            log.info("从 BaseContext 获取的 userId: {}", userId); // 添加此行日志
            if (userId == null) {
                return Result.error("无法获取用户ID");
            }

            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getUserId, userId);
            boolean updateResult = usersService.update(userToUpdate, qw);

            if (updateResult) {
                return Result.success(url);
            } else {
                return Result.error("更新头像失败");
            }
        } catch (IOException e) {
            log.info("文件上传失败:{}", e.getMessage());
        }
        //  返回文件上传失败
        return Result.error("上传失败");
    }
}
